// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW.sound {
	
	/**
	 * SoundTrack: Contains and controls a collection of sounds.
	 * @author Dale J Williams
	 */
	public class SoundTrack {
		
		private var _name			:String;
		private var _sounds			:Vector.<SoundObject>;
		
		private var _volume			:Number;
		private var _volumeAbs		:Number;
		
		private var _manager		:SoundManager;
		
		private var _numChannels	:int;
		private var _fadeTime		:Number;
		
		public function SoundTrack($name:String, $numChannels:int=-1, $fadeTime:Number=0, $volume:Number=1) {
			_name = $name;
			_numChannels = $numChannels;
			_fadeTime = $fadeTime;
			_volume = _volumeAbs = $volume;
			init();
		}
		
		private function init():void {
			_sounds = new Vector.<SoundObject>();
		}
		
		public function playSound($sound:SoundObject):void {
			if ($sound.track == this && $sound.playing && $sound.looping) {
				$sound.cancelFade();
				return;
			}
			_sounds.push($sound);
			if (_numChannels > 0 && _sounds.length > _numChannels)
				stopSound(_sounds.shift());
			$sound.track = this;
			$sound.rewind();
			$sound.play();
		}
		
		public function stopSound($sound:SoundObject, $hardStop:Boolean = false):void {
			if (!$hardStop && _fadeTime > 0)
				$sound.fadeOut(_fadeTime);
			else {
				$sound.stop();
				var i:int = _sounds.length;
				while (i--) 
					if (_sounds[i] == $sound)
						_sounds.splice(i, 1);
			}
		}
		
		public function stopAllSounds($hardStop:Boolean=false):void {
			for each(var sound:SoundObject in _sounds)
				stopSound(sound, $hardStop);
		}
		
		public function updateVolume():void {
			_volumeAbs = _volume * _manager.volume;
			for each(var sound:SoundObject in _sounds)
				sound.updateVolume();
		}
		
		public function get name():String { return _name; }		
		
		public function get volume():Number { return _volume; }		
		public function set volume(value:Number):void {
			_volume = value;
			updateVolume();
		}
		
		public function get manager():SoundManager { return _manager; }		
		public function set manager(value:SoundManager):void {
			_manager = value;
			updateVolume();
		}
		
		public function get volumeAbs():Number { return _volumeAbs; }
		
		public function get sounds():Vector.<SoundObject> { return _sounds; }
		
	}

}